<?php

namespace App\Repository\Sms;

use App\Api\Sms\SmsClient;
use App\Models\Sms\SmstmpModel as model;
use App\Repository\BaseRepository;
use App\Repository\Product\ProductRepository;

class SmsTmpRepository extends BaseRepository
{
    public function __construct()
    {
        $this->model = new model();
        $this->productModel = new ProductRepository();
        parent::__construct();
    }

    //列表
    public function index($where)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'id', 'orderdir' => 'desc'];
        // $cron['where'] = $where;
        // var_dump($cron,111111111);

        $data = $this->search($this->model, $cron, 1, 9000000);
        if (!empty($data['data'])) {
            $data['data'] = usfirstArr($data['data']);

        }
        $data['typeList'] = config('card.smsType');
        $data['useTypeList'] = config('card.smsUseType');
        $data['verifyStatusList'] = config('card.smsTplVerifyStatus');
        $data['smsTplParams'] = config('card.smsTplParams');
        return $data;
    }

    public function refresh($tplId, $tplType = 3)
    {
        $SmsApi = new SmsClient();
        $res = $SmsApi->queryTpl($tplId, $tplType);
        if ($res['code'] !== 200) {
            return $this->returnMsg(1, '获取接口数据失败');
        }
        $upData = [
            'verify_status' => $res['data']['verifyStatus'],
        ];
        $this->model->where(['tpl_id' => $tplId])->update($upData);
        return $this->returnMsg(200, '接口审核状态已同步', $upData);
    }

    //添加
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'name',
            'type',
            'content'
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'name' => '模版名称不能为空',
            'type' => '短信类型不能为空',
            'useType' => '模版使用类型不能为空',
            'content' => '模版内容不能为空'
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        $isTrue = $this->getOne(['name' => $insertData['name'], 'shop_id' => $data->user->shop_id]);
        if ($isTrue) {
            return $this->returnMsg(3, '该模板已添加');
        }
        $insertData['created_at'] = date('Y-m-d H:i:s');
        $insertData['created_by'] = $data->user->id;
        $insertData['created_by_name'] = $data->user->name;
        $insertData['use_type'] = $data->useType;
        $insertData['shop_id'] = (!empty($data->user->shop_id) ? $data->user->shop_id : (!empty($data->user->id) ? $data->user->id : ''));
//把数据提交到审核
        $SmsApi = new SmsClient();
        // $res = $SmsApi->addTpl($insertData['name'], $insertData['type'], $insertData['content']);
        $res = [
            'code' =>200,
            'data' => [
                'templateId' =>3,
            ],
        ];
        if ($res['code'] !== 200) {
            return $this->returnMsg(1, '上传接口失败');
        }
        $insertData['tpl_id'] = $res['data']['templateId'];
        $res = $this->model->insert($insertData);
        if ($res) {
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }

//    更换接口时重新提交审核
    public function makeResetCheck($data, $newName, $newContent = '')
    {
        if (!$data) {
            return $this->returnMsg(3, '该模板查询为空');
        }
        $id = $data['id'];
        //把数据提交到审核
        $SmsApi = new SmsClient();
        $res = $SmsApi->addTpl($data['name'], $data['type'], $data['content']);
        if ($res['code'] !== 200) {
            return $this->returnMsg(1, '上传接口审核失败');
        }
        if (empty($res['data']['templateId'])) {
            return $this->returnMsg(1, '上传模板失败');
        }
        $upData = [
            'tpl_id' => $res['data']['templateId'],
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => $data->user->id,
            'created_by_name' => $data->user->name,
            'verify_status' => 1,
            'name' => $newName,
            'content' => $newContent
        ];
//        print_r($upData);
        $res = $this->model->where(['id' => $id])->update($upData);
//        echo $this->getLastSql();
        if ($res) {
            return $this->returnMsg(200, '重新提交审核成功');
        }
        return $this->returnMsg(1, '添加失败');
    }

    //删除
    public function del($where)
    {
        $flag = true;
        $msg = '未知错误';
        $code = 1;
        if (empty($where)) {
            $flag = false;
            $msg = '删除条件不能为空';
            $code = 2;
        }
        if ($flag) {
            $res = $this->model->where($where)->get();
            if (!$res) {
                $flag = false;
                $msg = '未查询到数据';
                $code = 3;
            }
        }
        if ($flag) {
            $del = $this->model->where($where)->delete();
            if ($del) {
                $msg = '删除成功';
                $code = 200;
            }
        }
        return $this->returnMsg($code, $msg);
    }

    //修改
    public function edit($where, $data, $isMust = false)
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        //过滤字段
        //过滤字段
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        //把数据提交到审核
        $row = $this->model->where($where)->first();
        if (empty($row)) {
            return $this->returnMsg(1, '修改数据为空');
        }

//        重新提交审核
        if ($row['tpl_id'] <= 0 || empty($row['tpl_id'])) {
            return $this->makeResetCheck($data, $field['name'], $field['content']);
        }
        $SmsApi = new SmsClient();
        $tplId = $data['tplId'];
        $res = $SmsApi->editTpl($tplId, $row['type'], $field['name'], $field['content']);
        if ($res['code'] !== 200) {
            return $res;
        }
        $field['verify_status'] = 1;
        $field['use_type'] = $data['useType'] ?? 0;
        //先查询是否存在
        $res = $this->model->where($where)->update($field);
        if ($isMust && false !== $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }

    //列表查询
    public function lists($where = [], $page = 1, $limit = 10)
    {
        $res = $this->search($this->model, $where, $page, $limit);

        return $res;
    }

    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }

    //分销商获取供应商的商品信息
    public function addSuppilerGoods($data)
    {
        if (empty($data['goods_id'])) {
            return $this->returnMsg(1, '未查询到商品');
        }
        $where = [
            'id' => $data['goods_id'],
        ];
        $godsData = $this->getOne($where, ['name', 'goods_code', 'product_code', 'product_name', 'product_id', 'goods_point', 'settle_require', 'main_pic', 'goods_detail', 'goods_remark', 'remark', 'shop_str', 'goods_str', 'down_str']);
        if (empty($godsData)) {
            return $this->returnMsg(2, '未查询到商品');
        }
        $goodsData = json_decode(json_encode($godsData), true);
        $goodsData['shop_id'] = $data['user']['shop_id'];
        $goodsData['goods_str'] = trim($goodsData['goods_str'], '.') . '.' . $data['goods_id'] . '.';
        //判断他是否存在
        $isTrue = $this->getOne(['goods_str' => $goodsData['goods_str']]);
        if ($isTrue) {
            return $this->returnMsg(3, '您已将这个产品添加到该产品中');
        }
        // 修改上游的str
        $update = ['down_str' => trim($godsData['down_str'], '.') . '.' . $data['user']['shop_id'] . '.'];
        $this->edit(['id' => $data['goods_id']], $update);
        $goodsData['shop_str'] = trim($goodsData['shop_str'], '.') . '.' . $data['shopId'] . '.';
        $goodsData['created_by'] = $data['user']['id'];
        $goodsData['created_by_name'] = $data['user']['name'];
        $goodsData['created_at'] = date('Y-m-d H:i:s');
        $res = $this->model->insert($goodsData);
        if ($res) {
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }
}
